package com.colin.dubbo.strategy.context;

import com.colin.dubbo.annotation.MethodName;
import com.colin.dubbo.enums.MethodEnum;
import com.colin.dubbo.strategy.HandleStrategy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

@Component
public class HandleStrategyContext {
    
    private final Map<MethodEnum, HandleStrategy> handles = new ConcurrentHashMap<>();

    /**
     * spring会自动按照 Map<beanName, beanType>的方式将同一service下的bean注入
     */
    public HandleStrategyContext(Map<String, HandleStrategy> strategys){
        for(String strategyName : strategys.keySet()){
            HandleStrategy strategy = strategys.get(strategyName);
            MethodName annotation = AnnotationUtils.findAnnotation(strategy.getClass(), MethodName.class);
            if(annotation != null){
                handles.put(annotation.method(), strategy);
            }
        }
    }

    /**
     * 根据方法枚举获取对应的策略
     */
    public HandleStrategy getStrategy(MethodEnum methodEnum){
        return handles.get(methodEnum);
    }
    
}
